﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;


namespace 后台项目测试
{
    public class CacheHelper
    {
        ObjectCache oc = MemoryCache.Default;
        
        private static Dictionary<string, object> cacheDictionary = new Dictionary<string, object>();
        public static void Add(string key,object value)
        {
            cacheDictionary.Add(key, value);
        }
        public static T Get<T>(string key)
        {
            return (T)cacheDictionary[key];
        }
        public static T GetCache<T>(string key,Func<T> func)
        {
            T t = default(T);
            if (Exsits(key))
            {
                //缓存存在，直接获取原数据
                t = CacheHelper.Get<T>(key);
            }
            else
            {
                //缓存不存在，去生成缓存，并加入容器
                t = func.Invoke();
                CacheHelper.Add(key, t);
            }
            return t;
        }
        public static bool Exsits(string key)
        {
            return cacheDictionary.ContainsKey(key);
        }
    }
    public class DataSource
    {
        /// <summary>
        /// 模拟从数据库读取数据
        /// 耗时、耗CPU
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public static int GetDataByDB(int count)
        {
            Console.WriteLine("-----GetDataByDB----------");
            int result = 0;
            for (int i = count; i < 99999999; i++)
            {
                result += i;
            }
            System.Threading.Thread.Sleep(2000);
            return result;
        }
    }
}
